package com.sfh.story;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.sfh.story.entrty.Story;

/**
 * 添加故事内容到服务器
 * @author sWX229906
 *
 */
public class AddStory
{
    
    public String ADD_STROY_URL = "http://115.29.19.169/Admin.php/Story/addStory";
    
    String story_Name;
    
    int story_Type = 1;
    
    
    public String add(Story story)
        throws Exception
    {
        
        story_Name = story.name;
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("story_Name", story_Name));
        params.add(new BasicNameValuePair("story_Type", story_Type + ""));
        
        for (int i = 0; i < story.content.size(); i++)
        {
            params.add(new BasicNameValuePair(String.format("story_Content_%s", (i + 1)), story.content.get(i)));
        }
        
        return  requestByHttpPost(params);
        
    }
    
    /**获取任意图片*/
    private String get(List<String> imgs)
    {
        String story_Icon = "http://imgt0.bdstatic.com/it/u=3789063740,2873733824&amp;amp;fm=21&amp;amp;gp=0.jpg";
        int size = imgs.size();
        int rand = (int)Math.round(Math.random() * size);
        if (size > 0)
        {
            story_Icon = imgs.get(rand);
        }
        return story_Icon;
    }
    
    /***
     * 网络请求添加
     * @param params
     * @throws Exception
     */
    private String requestByHttpPost(List<NameValuePair> params)
        throws Exception
    {
        String result = "-1";
        HttpPost httpPost = new HttpPost(ADD_STROY_URL);
        HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        httpPost.setEntity(entity);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResp = httpClient.execute(httpPost);
        if (httpResp.getStatusLine().getStatusCode() == 200)
        {
           result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Log.i("", "HttpPost =" + result);
        }
        else
        {
            Log.i("", "HttpPost error");
        }
        
        return result;
    }
}
